import axios from 'axios'
import type { ApiResponse, PaginationResponse, QueryParams } from '@/types'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response?.status === 401) {
      // 未授权，跳转到登录页
      localStorage.removeItem('access_token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 通用API方法
export const apiClient = {
  get: <T = any>(url: string, params?: QueryParams): Promise<ApiResponse<T>> => {
    return api.get(url, { params })
  },

  post: <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return api.post(url, data)
  },

  put: <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return api.put(url, data)
  },

  delete: <T = any>(url: string): Promise<ApiResponse<T>> => {
    return api.delete(url)
  },

  // 分页查询
  getPaginated: <T = any>(url: string, params?: QueryParams): Promise<ApiResponse<PaginationResponse<T>>> => {
    return api.get(url, { params })
  },
}

export default api 